package org.algorithm.Sort;

import java.util.Arrays;

public class InsertionSort {
    public static void InsertionSort(int[] nums) {
        int n = nums.length;
        for (int i = 1; i < n; i++) {
            int temp = nums[i];
            int j = i - 1;
            //找到合适的插入位置
            for (; j >= 0; j--) {
                if (temp > nums[j]) {
                    break;
                } else {
                    nums[j + 1] = nums[j];
                }
            }
            //通过遍历，找到比temp小的值是nums[j]，所以temp的位置是j+1
            nums[j + 1] = temp;
        }
    }

    public static void main(String[] args) {
        int[] a = {10, 9, 7, 4, 3, 2, 1, 8};
        InsertionSort(a);

        System.out.println(Arrays.toString(a));
    }
}
